package cn.yj.config.web;

import cn.yj.cgs.dba.entity.Customer;
import cn.yj.common.Enums;
import cn.yj.commons.utils.StringUtils;
import cn.yj.config.annotation.Anonymous;
import cn.yj.core.business.service.CustomerService;
import cn.yj.entity.R;
import cn.yj.syslog.entity.SysLog;
import cn.yj.tools.exception.Error;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 放行不校验接口
 *
 * @author 永健
 * @since 2021-04-29 15:34
 */
@Order(-1)
@Component
public class AuthInterceptor extends AbstractInterceptor implements ApplicationContextAware {

    @Override
    public boolean doPreHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("Authorization");

        if (!exitsAnnotation(handler, Anonymous.class)) {
            if (matches(request.getRequestURI())) {
                return true;
            }
            if (StringUtils.isBlank(authorization)) {
                return setHttpResponse(R.error(Error.请求凭证有误.getCode(), Error.请求凭证有误.getErrMsg()), response);
            }
            Customer customer = customerService.getCustomByMiniOpenId(authorization);
            if (StringUtils.isNull(customer)) {
                return setHttpResponse(R.error(Error.请求凭证有误.getCode(), Error.请求凭证有误.getErrMsg()), response);
            }

            if (Enums.Common.TRUE_V.equals(customer.getUserStatus())) {
                return setHttpResponse(R.error(Error.操作失败.getCode(), "账户异常，请联系网站客服"), response);
            }
            request.setAttribute("currentUser", customer);
            // 日志操作用户
            request.setAttribute("user", customer.getRealName().concat("@").concat(customer.getUserCode()));
            return true;
        }

        // 不存在的话
        if (!StringUtils.isBlank(authorization)) {
            Customer customer = customerService.getCustomByMiniOpenId(authorization);
            if (!StringUtils.isNull(customer)) {
                request.setAttribute("currentUser", customer);
                // 日志操作用户
                request.setAttribute("user", customer.getRealName().concat("@").concat(customer.getUserCode()));
            }
        }
        return true;
    }

    private static CustomerService customerService;

    @Override
    public void setApplicationContext(ApplicationContext app) throws BeansException {
        try {
            customerService = app.getBean(CustomerService.class);
        } catch (BeansException e) {
            e.printStackTrace();
        }
    }
}
